package com.liuceng.zen.web.auth.utils;

import com.google.common.collect.Maps;
import com.liuceng.zen.common.utils.Digests;
import com.liuceng.zen.common.utils.EhCacheUtils;
import com.liuceng.zen.common.utils.Encodes;
import com.liuceng.zen.service.AccountService;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * AuthUtils.java
 * 
 * @author ryenlea
 */
@Service
public class AuthUtils {

  public static boolean processValidateCode(String useruame, boolean isFail, boolean clean) {
    Map<String, Integer> loginFailMap = (Map<String, Integer>) EhCacheUtils.get("loginFailMap");
    if (loginFailMap == null) {
      loginFailMap = Maps.newHashMap();
      EhCacheUtils.put("loginFailMap", loginFailMap);
    }
    Integer loginFailNum = loginFailMap.get(useruame);
    if (loginFailNum == null) {
      loginFailNum = 0;
    }
    if (isFail) {
      loginFailNum++;
      loginFailMap.put(useruame, loginFailNum);
    }
    if (clean) {
      loginFailMap.remove(useruame);
    }
    return loginFailNum >= 3;
  }

  public static String encryptPlainPassword(String plainPassword, byte[] salt) {
    byte[] hashedPassword =
        Digests.sha1(plainPassword.getBytes(), salt, AccountService.HASH_INTERATIONS);
    return Encodes.encodeHex(hashedPassword);
  }

  public static String[] generateSaltAndPassword(String plainPassword) {
    byte[] salt = Digests.generateSalt(AccountService.SALT_SIZE);
    //
    String saltStr = Encodes.encodeHex(salt);
    String hashedPasswordStr = encryptPlainPassword(plainPassword, salt);
    //
    return new String[] {saltStr, hashedPasswordStr};
  }
}
